package org.looop.studio.noots.advantage;

import java.io.IOException;
import java.text.DecimalFormat;

import org.apache.commons.lang.StringUtils;
import org.apache.lucene.document.Document;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Sort;
import org.apache.lucene.store.Directory;

public class SearchResultViewer {
	private Directory directory;

	public SearchResultViewer(Directory directory) {
		super();
		this.directory = directory;
	}
	
	public void displayHits(Query query, Sort sort) throws IOException {
		IndexSearcher searcher = new IndexSearcher(directory);
		Hits hits = searcher.search(query, sort);
		System.out.println("\nResults for: " + query.toString() + " sorted by " + sort);
		System.out.println(StringUtils.rightPad("Title", 30) + StringUtils.rightPad("pubmonth", 10) + StringUtils.center("id", 4) + StringUtils.center("score", 15));
		
		DecimalFormat scoreFormatter = new DecimalFormat("0.######");
		for (int i = 0; i < hits.length(); i++) {
			Document doc = hits.doc(i);
			System.out.println(StringUtils.rightPad(StringUtils.abbreviate(doc.get("title"), 29), 30) + StringUtils.rightPad(doc.get("pubmonth"), 10) + StringUtils.center("" + hits.id(i), 4) + StringUtils.leftPad(scoreFormatter.format(hits.score(i)), 12));
			System.out.println("\t" + doc.get("category"));
		}
		searcher.close();
		
	}
}
